package crond

import (
	"strconv"
	"strings"
	"time"

	"device-admin/config/mysql"
	"device-admin/internal/models"
)

// ActiveDurationReport 活跃时长统计
// 遍历每台设备的活跃时长记录，累计保存到设备表
// 当前时长=历史累计+今日累计（实时获取）
func ActiveDurationReport() {
	db := mysql.NewDB()

	// 获取设备记录
	var devices []models.Device
	db.Model(&models.Device{}).Find(&devices)

	// 遍历每台设备的活跃记录
	for _, device := range devices {
		var temp models.DeviceActiveDuration
		// 活跃数据汇总
		{
			year := strconv.Itoa(int(time.Now().Year()))
			month := strconv.Itoa(int(time.Now().Month()))
			day := strconv.Itoa(int(time.Now().Day()))
			today := strings.Join([]string{year, month, day}, "-")
			db.Model(&models.DeviceActiveDuration{}).
				Select(
					"SUM(running_odometer) as running_odometer",
					"SUM(running_duration) as running_duration",
					"SUM(charging_duration) as charging_duration",
					"SUM(idle_duration) as idle_duration",
				).
				Where("robot_id = ?", device.RobotID).
				Where("date <> ?", today).
				Group("robot_id").
				Take(&temp)
		}

		// 任务里程汇总
		var taskRecord models.TaskRecord
		{
			// 获取今天的日期
			today := time.Now().Format("2006-01-02") // 注意，这个有别上面的today，上面的today是为了兼容设备上报的格式（不满两位的，不补0）
			db.Model(&models.TaskRecord{}).
				Select(
					"SUM(odometer) as odometer",
					"SUM(time_duration) as time_duration",
				).
				Where("robot_id = ?", device.RobotID).
				Where("created_date <> ?", today).
				Group("robot_id").
				Take(&taskRecord)
		}

		// 缓存至数据库
		db.Model(&models.Device{}).
			Where("robot_id = ?", device.RobotID).
			Updates(&models.Device{
				TotalRunningOdometer:  temp.RunningOdometer,
				TotalRunningDuration:  temp.RunningDuration,
				TotalChargingDuration: temp.ChargingDuration,
				TotalIdleDuration:     temp.IdleDuration,
				TotalTaskOdometer:     taskRecord.Odometer,
				TotalTaskDuration:     taskRecord.TimeDuration,
			})
	}
}
